import isArray from 'lodash/isArray'
import { ElMessage } from 'element-plus'
import trim from 'lodash/trim'
import { translateTitle } from '@/utils/i18n'
//必须带done回调 执行完成调用
export default function getFormData({ vm, action, done, eventName }) {
  if (action.extension.formSelect.value.length > 0) {
    // console.log(action.extension.formSelect)
    let formDatas = {}
    let self = null
    action.extension.formSelect.value.forEach((item) => {
      // console.log(vm.vuiComponents[item])
      self = vm.vuiComponents[item]?.self
      if (self) {
        if (self.getInfo.type == 'uiCirculationForm') {
          formDatas = self.getInfo.data.requestListData
        } else if (isArray(self.getInfo.data.formData)) {
          formDatas = self.getInfo.data.formData
        } else {
          let formData = {}
          // 通过获取数据key筛选数据
          console.log('获取值的表单组件 -------------------------- ', self)
          if (action.extension.getDataKey && action.extension.getDataKey.value) {
            action.extension.getDataKey.value.split(',').forEach((keyItem) => {
              keyItem = trim(keyItem)
              formData[keyItem] = self.getInfo.data.formData[keyItem]
            })
          } else {
            formData = self.getInfo.data.formData
          }
          formDatas = Object.assign(formDatas, formData)
          // 合并老值
          if (action.extension.getOldValueKey && action.extension.getOldValueKey.value) {
            action.extension.getOldValueKey.value.split(',').forEach((keyItem) => {
              keyItem = trim(keyItem)
              if (self.getInfo.data._formData && self.getInfo.data._formData[keyItem] !== undefined) {
                formDatas[`old_${keyItem}`] = self.getInfo.data._formData[keyItem]
              }
            })
          }
        }
      }
    })
    if (self) {
      // 存储动作数据
      vm.$store.dispatch('actionDatas/setActionsData', {
        moduleId: vm.info._id,
        actionId: action._id,
        actionData: formDatas,
      })
      done(null, formDatas)
    } else {
      ElMessage({
        showClose: true,
        message: translateTitle('Ve.eventTask.获取表单值提示'),
        type: 'error',
      })
      // 修改任务队列执行状态，防止下一次事件被拦截
      vm[`${eventName}IsRunning`] = false
    }
  } else {
    done(null, {})
  }
}
